package com.wys.filter;

import com.alibaba.fastjson.JSON;
import com.wys.common.BaseContext;
import com.wys.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //得到本次拦截的路径
        String requestURI = request.getRequestURI();
        log.info("拦截到{}",requestURI);
        //定义不需要处理的资源
        String [] urls = {"/employee/login","/employee/logout","/backend/**","/front/**","/user/login","/user/sendMsg"};
        //检查本次的资源是否需要处理
        boolean check = check(requestURI, urls);
        if(check){
            //资源不需要处理，直接放行
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //资源需要处理，检查是否登录
        if( request.getSession().getAttribute("employee") != null){
            log.info("登陆的用户ID为{}",request.getSession().getAttribute("employee"));
            //将登陆的用户ID存入线程，以便以后使用
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setThreadLocal(id);
            //已经登陆，直接放行
            filterChain.doFilter(request,response);
            return;
        }

        //资源需要处理，检查是否登录(用户端)
        if( request.getSession().getAttribute("user") != null){
            log.info("登陆的用户ID为{}",request.getSession().getAttribute("user"));
            //将登陆的用户ID存入线程，以便以后使用
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setThreadLocal(userId);
            //已经登陆，直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //资源需要处理，且没有登陆，返回结果
        log.info("用户未登录！");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     *  检查资源是否需要处理
     * @param requestURI
     * @param urls
     * @return
     */
    public boolean check(String requestURI,String [] urls){
        for (String url : urls) {
            boolean flag = PATH_MATCHER.match(url, requestURI);
            if(flag){
                return true;
            }
        }
        return false;
    }
}
